package com.demon.framework.util.request;

import com.alibaba.fastjson.JSONObject;
import com.demon.framework.common.model.constants.HeaderConstants;
import com.demon.framework.common.model.entity.ClientInfo;
import com.demon.framework.util.net.IpUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.Enumeration;

/**
 * 客户端信息 工具类
 *
 * @author Demon-HY
 * @date 2020/5/22
 */
public class ClientInfoUtil {

    /**
     * 获取客户端信息
     *
     * @return 为空不会抛出异常, 返回 null
     */
    public static ClientInfo getClientInfo() {
        try {
            HttpServletRequest request = RequestContextUtil.request();
            if (request != null) {
                Enumeration<String> clientInfos = request.getHeaders(HeaderConstants.CLIENT);
                if (clientInfos.hasMoreElements()) {
                    String clientInfoUnicode = clientInfos.nextElement();
                    String clientInfo = URLDecoder.decode(clientInfoUnicode, "UTF-8");
                    ClientInfo result = JSONObject.parseObject(clientInfo, ClientInfo.class);
                    result.setIp(IpUtils.getIpAddr(request));
                    return result;
                }
            }
        } catch (Exception ignored) {
        }

        return null;
    }
}
